<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我的收藏',
  },
}
</route>

<script lang="ts" setup>
import FgFooter from '@/components/fg-footer/fg-footer.vue'
import { useUserStore } from '@/store/user'

defineOptions({
  name: 'Favorites',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 用户登录状态
const isLoggedIn = ref(false)
const userInfo = ref<any>(null)

// 收藏列表
const favoriteList = ref<any[]>([])
const isLoading = ref(false)

// 检查登录状态
function checkLoginStatus() {
  // 这里应该从 store 或本地存储获取用户信息
  const userStore = useUserStore()
  const user = userStore.userInfo

  if (user && user.token) {
    isLoggedIn.value = true
    userInfo.value = user
    loadFavorites()
  }
  else {
    isLoggedIn.value = false
    userInfo.value = null
  }
}

// 加载收藏列表
async function loadFavorites() {
  if (!isLoggedIn.value)
    return

  console.log('开始加载收藏列表...')
  isLoading.value = true
  try {
    // 使用API服务而不是直接的uni.request，确保token正确传递
    const { userCenterGet3 } = await import('@/service/app/userCenter')
    const response = await userCenterGet3({
      params: {},
    })

    console.log('收藏API响应:', response)
    console.log('response.success:', response?.success)
    console.log('response.data:', response?.data)
    console.log('response.data?.data:', response?.data?.data)

    if (response?.success) {
      favoriteList.value = response.data?.data || []
      console.log('设置收藏列表:', favoriteList.value)
    }
    else {
      console.log('API调用失败，success为false')
      uni.showToast({
        title: '加载收藏失败',
        icon: 'none',
      })
    }
  }
  catch (error: any) {
    console.error('加载收藏失败:', error)
    // 检查是否是401错误（token过期）
    if (error?.statusCode === 401) {
      uni.showToast({
        title: '登录信息已过期，请重新登录',
        icon: 'none',
        duration: 2000,
      })
      // 清理用户状态
      const userStore = useUserStore()
      userStore.removeUserInfo()
      isLoggedIn.value = false
      userInfo.value = null
    }
    else {
      uni.showToast({
        title: '加载收藏失败',
        icon: 'none',
      })
    }
  }
  finally {
    isLoading.value = false
  }
}

// 取消收藏
async function removeFavorite(itemId: number) {
  try {
    // 使用收藏接口，通过action参数实现取消收藏
    const { userCenterFavorite } = await import('@/service/app/userCenter')
    const response = await userCenterFavorite({
      params: {
        productId: itemId,
        action: 'remove',
      },
    })

    if (response?.success) {
      uni.showToast({
        title: '取消收藏成功',
        icon: 'success',
      })
      // 重新加载收藏列表
      loadFavorites()
    }
    else {
      uni.showToast({
        title: '取消收藏失败',
        icon: 'none',
      })
    }
  }
  catch (error: any) {
    console.error('取消收藏失败:', error)
    // 检查是否是401错误（token过期）
    if (error?.statusCode === 401) {
      uni.showToast({
        title: '登录信息已过期，请重新登录',
        icon: 'none',
        duration: 2000,
      })
      // 清理用户状态
      const userStore = useUserStore()
      userStore.removeUserInfo()
      isLoggedIn.value = false
      userInfo.value = null
    }
    else {
      uni.showToast({
        title: '取消收藏失败',
        icon: 'none',
      })
    }
  }
}

// 跳转到登录页
function goToLogin() {
  uni.navigateTo({
    url: '/pages/login/index',
  })
}

// 页面初始化
onMounted(() => {
  checkLoginStatus()
})
</script>

<template>
  <view>
    <!-- 未登录状态 -->
    <view v-if="!isLoggedIn" class="relative min-h-screen">
      <!-- 顶部蓝色导航区域 -->
      <view class="relative overflow-hidden from-blue-600 to-blue-800 bg-gradient-to-br px-6 py-20">
        <!-- 背景装饰图案 -->
        <view class="absolute inset-0 opacity-10">
          <view class="absolute right-4 top-4 h-16 w-16 rounded-full bg-white opacity-30" />
          <view class="absolute right-12 top-8 h-8 w-8 rounded-full bg-white opacity-20" />
          <view class="absolute right-20 top-12 h-12 w-12 rounded-full bg-white opacity-25" />
          <view class="absolute right-28 top-16 h-6 w-6 rounded-full bg-white opacity-15" />
          <view class="absolute right-36 top-20 h-10 w-10 rounded-full bg-white opacity-20" />
        </view>

        <!-- 登录提示卡片 -->
        <view
          class="relative z-10 flex items-center rounded-xl bg-white px-4 shadow-lg"
          @click="goToLogin"
        >
          <view class="mr-3 h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
            <text class="i-carbon-document text-lg text-blue-600" />
          </view>
          <view class="flex-1">
            <view class="text-lg text-gray-800 font-medium">
              立即登录
            </view>
          </view>
          <text class="i-carbon-arrow-right text-gray-400" />
        </view>
      </view>

      <!-- 空状态内容区域 -->
      <view
        class="flex flex-col items-center justify-center from-blue-50 to-white bg-gradient-to-b"
      >
        <view class="flex flex-col items-center">
          <view class="relative mb-6 mt-20">
            <view class="h-32 w-24 rotate-12 transform rounded-lg bg-white shadow-lg">
              <view
                class="absolute left-1/2 h-4 w-8 transform rounded-t-lg bg-gray-300 -top-4 -translate-x-1/2"
              />
              <!-- 线条 -->
              <view class="absolute left-4 right-4 top-8 h-0.5 bg-gray-300" />
              <view class="absolute left-4 right-4 top-12 h-0.5 bg-gray-300" />
              <view class="absolute left-4 right-4 top-16 h-0.5 bg-gray-300" />
            </view>

            <!-- 装饰性加号和点 -->
            <view
              class="absolute h-3 w-3 flex items-center justify-center rounded-full bg-gray-300 -right-2 -top-2"
            >
              <text class="text-xs text-white">
                +
              </text>
            </view>
            <view class="absolute top-4 h-2 w-2 rounded-full bg-gray-300 -right-4" />
            <view class="absolute top-8 h-2 w-2 rounded-full bg-gray-300 -right-6" />
            <view class="absolute top-12 h-2 w-2 rounded-full bg-gray-300 -right-4" />
            <view class="absolute top-16 h-2 w-2 rounded-full bg-gray-300 -right-2" />
            <view class="absolute top-20 h-2 w-2 rounded-full bg-gray-300 -right-4" />
            <view class="absolute top-24 h-2 w-2 rounded-full bg-gray-300 -right-6" />
          </view>

          <!-- 空状态文字 -->
          <view class="text-lg text-gray-500">
            收藏夹空空如也
          </view>
        </view>
      </view>
    </view>

    <!-- 已登录状态 -->
    <view v-else class="min-h-screen bg-gray-50">
      <!-- 头部区域 -->
      <view
        class="relative overflow-hidden from-blue-600 to-blue-800 bg-gradient-to-br px-6 pb-8 pt-4"
      >
        <!-- 背景装饰 -->
        <view class="absolute inset-0 opacity-20">
          <view class="absolute right-4 top-4 h-16 w-16 rounded-full bg-white opacity-30" />
          <view class="absolute right-12 top-8 h-8 w-8 rounded-full bg-white opacity-20" />
          <view class="absolute right-20 top-12 h-12 w-12 rounded-full bg-white opacity-25" />
        </view>

        <!-- 用户信息卡片 -->
        <view class="relative z-10 mt-4 flex items-center rounded-xl bg-white px-4 py-3 shadow-lg">
          <view class="mr-3 h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
            <text class="i-carbon-user text-lg text-blue-600" />
          </view>
          <view class="flex-1">
            <view class="text-sm text-gray-500">
              用户ID
            </view>
            <view class="text-lg text-gray-800 font-medium">
              {{ userInfo?.userId || '用户' }}{{ userInfo?.id || '' }}
            </view>
          </view>
        </view>
      </view>

      <!-- 收藏列表 -->
      <view class="px-4 pb-20">
        <view v-if="isLoading" class="py-20 text-center">
          <text class="i-carbon-loading animate-spin text-2xl text-gray-400" />
          <view class="mt-2 text-sm text-gray-500">
            加载中...
          </view>
        </view>

        <view v-else-if="favoriteList.length === 0" class="py-20 text-center">
          <view
            class="mx-auto mb-4 h-24 w-24 flex items-center justify-center rounded-full bg-gray-100"
          >
            <text class="i-carbon-favorite text-4xl text-gray-400" />
          </view>
          <view class="text-gray-500">
            暂无收藏内容
          </view>
        </view>

        <view v-else class="space-y-4">
          <view
            v-for="item in favoriteList"
            :key="item.id"
            class="rounded-xl bg-white p-4 shadow-sm"
          >
            <!-- 产品信息 -->
            <view class="flex">
              <!-- 产品图片 -->
              <view class="mr-4 h-20 w-20 flex-shrink-0 overflow-hidden rounded-lg">
                <image
                  :src="
                    item.mainPhotoes?.[0]?.attachmentAddress || '/static/images/default-avatar.png'
                  "
                  class="h-full w-full object-cover"
                  mode="aspectFill"
                />
                <!-- 标签 -->
                <view
                  class="absolute left-1 top-1 rounded bg-blue-500 px-2 py-1 text-xs text-white"
                >
                  厂家直销
                </view>
                <view
                  class="absolute bottom-1 right-1 rounded bg-blue-500 px-2 py-1 text-xs text-white"
                >
                  专注激光切割机
                </view>
              </view>

              <!-- 产品详情 -->
              <view class="flex-1">
                <view class="mb-2 text-lg text-gray-800 font-semibold">
                  {{ item.productName || '产品名称' }}
                </view>
                <view class="mb-2 text-sm text-gray-600">
                  品牌: {{ item.brand || '未知' }} 型号: {{ item.model || '未知' }}
                </view>
                <view class="mb-2 text-sm text-gray-800">
                  等级认证: {{ item.gradeName || item.grade || 'A级' }}
                </view>

                <!-- 等级指示条 -->
                <view class="mb-3 h-2 flex overflow-hidden rounded-full">
                  <view class="flex-1 bg-green-500" />
                  <view class="flex-1 bg-green-300" />
                  <view class="flex-1 bg-yellow-400" />
                  <view class="flex-1 bg-red-400" />
                </view>

                <!-- 操作按钮 -->
                <view class="flex justify-end">
                  <view
                    class="rounded bg-red-500 px-4 py-2 text-sm text-white"
                    @click="removeFavorite(item.id)"
                  >
                    取消收藏
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <FgFooter />
  </view>
</template>
